package com.zwp.base.state

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.*
import com.zwp.base.BR
import kotlinx.coroutines.launch


class StateModelController(
    val context: Context,
    val lifecycleOwner: LifecycleOwner,
    var layoutResId: Int,
    var stateModel: StateModel,
    val stateContainerProcessor: IStateContainerProcessor
) {

    var dataBinding: ViewDataBinding? = null

    init {
        stateModel.onEmptyStateChangeListener = object : OnEmptyStateChangeListener {
            override fun onChange(emptyState: EmptyState) {
                if (emptyState == EmptyState.NORMAL) {
                    remove()
                } else {
                    checkAddStateLayout()
                }
            }
        }
        lifecycleOwner.lifecycleScope.launch {
            lifecycleOwner.repeatOnLifecycle(Lifecycle.State.DESTROYED) {
//                stateModel.onEmptyStateChangeListener = null
                dataBinding?.unbind()
            }
        }
    }

    fun hasShow() = dataBinding != null && dataBinding?.root?.parent != null

    fun remove() {
        if (hasShow()) {
            stateContainerProcessor.removeStateModelView(dataBinding!!.root)
        }
    }

    fun checkAddStateLayout() {
        if (hasShow()) return

        if (dataBinding == null) {
            dataBinding =
                DataBindingUtil.inflate(LayoutInflater.from(context), layoutResId, null, false)
            dataBinding!!.setVariable(BR.stateModel, stateModel)
        }
        stateContainerProcessor.addStateModelView(dataBinding!!.root)
    }

}


